﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Castle.Core.Logging;
using ComponentFactory.Krypton.Toolkit;

namespace TVN.ShopMan.ApplicationInterface.AppForms
{
    using TVN.Common.Interfaces;
    using TVN.ShopMan.ActiveModels;

    public partial class SupplierForm : Form
    {
        private class ColumnIndex
        {
            public const int Id = 0;
            public const int Name = 1;
            public const int IsActive = 2;
        }

        private static readonly ILogger _logger = Program.Logger.CreateChildLogger("SupplierForm");
        private IRepository<Supplier> supplierRepository = null;
        private IList<Supplier> listOfSuppliers = null;
        private IList<Supplier> listOfSuppliersToDelete = null;

        public SupplierForm()
        {
            InitializeComponent();

            this.SetUp();
            this.LoadData();
        }

        /// <summary>
        /// Setup the data grid
        /// </summary>
        private void SetUp()
        {
            this.supplierRepository = Program.Container.Resolve<IRepository<Supplier>>();

            this.kdgvSuppliers.AutoGenerateColumns = false;
            var idColumn = new DataGridViewColumn
            {
                DataPropertyName = Supplier.Properties.Id,
                Name = Supplier.Properties.Id,
                HeaderText = "Id",
                ValueType = typeof(int),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = false
            };
            this.kdgvSuppliers.Columns.Add(idColumn);

            var nameColumn = new DataGridViewColumn
            {
                DataPropertyName = Supplier.Properties.Name,
                Name = Supplier.Properties.Name,
                HeaderText = "Supplier Name",
                ValueType = typeof(string),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true,
                MinimumWidth = 200
            };
            this.kdgvSuppliers.Columns.Add(nameColumn);

            var isActiveColumn = new DataGridViewColumn
            {
                DataPropertyName = Supplier.Properties.IsActive,
                Name = Supplier.Properties.IsActive,
                HeaderText = "Is active",
                ValueType = typeof(bool),
                CellTemplate = new DataGridViewCheckBoxCell(false),
                DefaultCellStyle = new DataGridViewCellStyle
                {
                    Alignment = DataGridViewContentAlignment.MiddleCenter
                },
                Visible = true
            };
            this.kdgvSuppliers.Columns.Add(isActiveColumn);
        }

        /// <summary>
        /// Load all units from database
        /// </summary>
        private void LoadData()
        {
            this.listOfSuppliers = this.supplierRepository.FindAll();
            if (this.listOfSuppliers == null)
            {
                this.listOfSuppliers = new List<Supplier>();
            }

            foreach (Supplier supplierItem in this.listOfSuppliers)
            {
                this.DisplaySupplierData(supplierItem);
            }
        }

        private DialogResult ConfirmRemoveSuppliers()
        {
            var result = DialogResult.None;
            if (this.kdgvSuppliers.SelectedRows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Are you sure you want to delete these suppliers:");
                sb.AppendLine();
                foreach (DataGridViewRow rowItem in this.kdgvSuppliers.SelectedRows)
                {
                    sb.AppendFormat("   {0}", rowItem.Cells[ColumnIndex.Name].Value);
                    sb.AppendLine();
                }

                result = KryptonMessageBox.Show(sb.ToString(), "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            }

            return result;
        }

        private void DisplaySupplierData(Supplier supplier)
        {
            if (supplier != null)
            {
                this.kdgvSuppliers.Rows.Add(supplier.Id, supplier.Name, supplier.IsActive);
            }
        }

        private void AddOrUpdateSupplier(Supplier supplier)
        {
            if (supplier != null)
            {
                Supplier existingSupplier = this.listOfSuppliers.FirstOrDefault(item => (item.Id == supplier.Id));
                if (existingSupplier == null)
                {
                    this.listOfSuppliers.Add(supplier);
                    this.DisplaySupplierData(supplier);
                }
                else
                {
                    existingSupplier = supplier;
                    this.UpdateSupplierData(supplier);
                }
            }
        }

        private void ShowSupplierForm(DataGridViewRow rowItem)
        {
            if (rowItem != null)
            {
                int supplierId = Convert.ToInt32(rowItem.Cells[ColumnIndex.Id].Value);
                string name = Convert.ToString(rowItem.Cells[ColumnIndex.Name].Value);

                Supplier accountItem = this.listOfSuppliers.FirstOrDefault(item => ((item.Id == supplierId) && (item.Name == name)));
                using (var supplierForm = new SupplierFormEdit(accountItem)
                {
                    StartPosition = FormStartPosition.CenterParent
                })
                {
                    var result = supplierForm.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        this.AddOrUpdateSupplier(supplierForm.SelectedSupplier);
                    }
                }
            }
        }

        private void UpdateSupplierData(Supplier supplier)
        {
            if (supplier != null)
            {
                foreach (DataGridViewRow rowItem in this.kdgvSuppliers.Rows)
                {
                    if (supplier.Id.Equals(rowItem.Cells[ColumnIndex.Id].Value))
                    {
                        rowItem.Cells[ColumnIndex.Name].Value = supplier.Name;
                        rowItem.Cells[ColumnIndex.IsActive].Value = supplier.IsActive;

                        break;
                    }
                }
            }
        }

        private void btnAddUnit_Click(object sender, EventArgs e)
        {
            using (var supplierForm = new SupplierFormEdit()
            {
                StartPosition = FormStartPosition.CenterParent
            })
            {
                var result = supplierForm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    this.AddOrUpdateSupplier(supplierForm.SelectedSupplier);
                }
            }
        }

        private void btnSaveChanges_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.listOfSuppliersToDelete != null)
                {
                    foreach (Supplier supplierItem in this.listOfSuppliersToDelete)
                    {
                        supplierItem.Delete();
                    }
                }

                if (this.listOfSuppliers != null)
                {
                    foreach (Supplier supplierItem in this.listOfSuppliers)
                    {
                        supplierItem.Save();
                    }
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
                this.Dispose();

                GC.SuppressFinalize(this);
            }
            catch (Exception ex)
            {
                this.DialogResult = DialogResult.No;
                _logger.Error("Error while saving changes", ex);
            }
        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.kdgvSuppliers.CurrentRow != null)
                {
                    this.ShowSupplierForm(this.kdgvSuppliers.CurrentRow);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error while updating account", ex);
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ConfirmRemoveSuppliers() == DialogResult.Yes)
            {
                foreach (DataGridViewRow rowItem in this.kdgvSuppliers.SelectedRows)
                {
                    this.kdgvSuppliers.Rows.Remove(rowItem);

                    // Add deleted rows into the list
                    int supplierId = Convert.ToInt32(rowItem.Cells[ColumnIndex.Id].Value);
                    string name = Convert.ToString(rowItem.Cells[ColumnIndex.Name].Value);
                    Supplier supplierItem = this.listOfSuppliers.FirstOrDefault(item => ((item.Id == supplierId) && (item.Name == name)));

                    if (this.listOfSuppliersToDelete == null)
                    {
                        this.listOfSuppliersToDelete = new List<Supplier>();
                    }
                    this.listOfSuppliersToDelete.Add(supplierItem);
                    this.listOfSuppliers.Remove(supplierItem);
                }
            }
        }

        private void kdgvSuppliers_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataGridViewCell modifiedCell = this.kdgvSuppliers.Rows[e.RowIndex].Cells[e.ColumnIndex];

                int supplierId = Convert.ToInt32(this.kdgvSuppliers.Rows[e.RowIndex].Cells[ColumnIndex.Id].Value);
                Supplier selectedSupplier = this.listOfSuppliers.FirstOrDefault(repositoryItem => repositoryItem.Id == supplierId);

                switch (e.ColumnIndex)
                {
                    case ColumnIndex.Name:
                        selectedSupplier.Name = Convert.ToString(modifiedCell.Value);
                        break;
                    case ColumnIndex.IsActive:
                        selectedSupplier.IsActive = Convert.ToBoolean(modifiedCell.Value);
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat(ex, "Error while editing cell: {0}", e.ColumnIndex);
            }
        }

        private void kdgvSuppliers_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            int supplierId = Convert.ToInt32(e.Row.Cells[ColumnIndex.Id].Value);
            string name = Convert.ToString(e.Row.Cells[ColumnIndex.Name].Value);
            Supplier accountItem = this.listOfSuppliers.FirstOrDefault(item => ((item.Id == supplierId) && (item.Name == name)));

            if (this.listOfSuppliersToDelete == null)
            {
                this.listOfSuppliersToDelete = new List<Supplier>();
            }
            this.listOfSuppliersToDelete.Add(accountItem);
        }

        private void kdgvSuppliers_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (this.ConfirmRemoveSuppliers() != DialogResult.Yes)
            {
                e.Cancel = true;
            }
        }
    }
}
